using CzJ_VoteSys.Configs;
using CzJ_VoteSys.Models.Configs;
using CzJ_VoteSys.Models.Database;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;

namespace CzJ_VoteSys
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        private IConfigurationSection jwtConfigSection;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            jwtConfigSection = Configuration.GetSection("JWTConfig");
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(logBuilder =>
            {
                logBuilder.ClearProviders();
                logBuilder.AddNLog();
            });

            services.Configure<JWTConfig>(jwtConfigSection);
            JwtBearerConfigure.Configure(services, jwtConfigSection.Get<JWTConfig>());

            services.AddSwaggerGen(SwaggerGenConfigure.Options);

            #region Services
            services.AddScoped<Services.IJWTService, Services.JWTService>();
            services.AddScoped<Services.UserService>();
            #endregion

            services.AddDbContext<CzJ_VoteSysContext>();
            services.AddControllers(x =>
            {
                x.Filters.Add<Filters.GlobalExceptionFilter>();
                x.Filters.Add<Filters.GlobalRESTfulActionFilter>();
            });

            services.Configure<ApiBehaviorOptions>(ApiBehaviorConfigure.Options);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            #region swagger
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "CzJ_VoteSys v1");
                c.RoutePrefix = "swagger";
            });
            #endregion

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
